import request from '@/utils/request'
import type { CdFileVo, CdFolderVo, CdShareVo } from '@/types/cd'

// 文件管理API
export interface FileQuery {
  folderId: number
  fileName?: string
  fileType?: string
  pageNum: number
  pageSize: number
}

export interface FileSearchQuery {
  keyword?: string
  fileType?: string
  pageNum: number
  pageSize: number
}

// 文件夹管理API
export interface FolderQuery {
  parentId: number
  folderName?: string
  folderType?: string
  pageNum: number
  pageSize: number
}

// 分享管理API
export interface ShareCreateParams {
  shareType: string
  resourceId: number
  shareName: string
  sharePassword?: string
  expireTime?: string
  accessLevel?: string
  allowDownload?: boolean
  allowPreview?: boolean
}

export interface ShareUpdateParams {
  shareId: number
  shareName: string
  sharePassword?: string
  expireTime?: string
  accessLevel?: string
  allowDownload?: boolean
  allowPreview?: boolean
}

/**
 * 文件管理API
 */
export const fileApi = {
  // 上传文件
  upload: (file: File, folderId: number | string) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('folderId', String(folderId))
    return request({
      url: '/cd/file/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 下载文件
  download: (fileId: number | string | bigint) => {
    return request({
      url: `/cd/file/download/${String(fileId)}`,
      method: 'get',
      responseType: 'blob'
    })
  },

  // 预览文件
  preview: (fileId: number | string | bigint) => {
    return request({
      url: `/cd/file/preview/${String(fileId)}`,
      method: 'get'
    })
  },

  // 重命名文件
  rename: (fileId: number | string | bigint, newName: string) => {
    return request({
      url: '/cd/file/rename',
      method: 'put',
      params: { fileId: String(fileId), newName }
    })
  },

  // 移动文件
  move: (fileId: number | string | bigint, targetFolderId: number | string | bigint) => {
    return request({
      url: '/cd/file/move',
      method: 'post',
      params: { fileId: String(fileId), targetFolderId: String(targetFolderId) }
    })
  },

  // 复制文件
  copy: (fileId: number | string | bigint, targetFolderId: number | string | bigint) => {
    return request({
      url: '/cd/file/copy',
      method: 'post',
      params: { fileId: String(fileId), targetFolderId: String(targetFolderId) }
    })
  },

  // 删除文件
  delete: (fileIds: (number | string | bigint)[]) => {
    const ids = fileIds.map(id => String(id)).join(',')
    return request({
      url: `/cd/file/${ids}`,
      method: 'delete'
    })
  },

  // 查询文件列表
  list: (params: FileQuery) => {
    return request({
      url: '/cd/file/list',
      method: 'get',
      params
    })
  },

  // 搜索文件
  search: (params: FileSearchQuery) => {
    return request({
      url: '/cd/file/search',
      method: 'get',
      params
    })
  },

  // 获取文件详情
  getInfo: (fileId: number | string | bigint) => {
    return request({
      url: `/cd/file/${String(fileId)}`,
      method: 'get'
    })
  },

  // 检查文件权限
  checkPermission: (fileId: number | string | bigint, permissionType: string) => {
    return request({
      url: `/cd/file/permission/${String(fileId)}`,
      method: 'get',
      params: { permissionType }
    })
  }
}

/**
 * 文件夹管理API
 */
export const folderApi = {
  // 创建文件夹
  create: (folderName: string, parentId: number | string, projectId?: number) => {
    return request({
      url: '/cd/folder/create',
      method: 'post',
      params: { folderName, parentIdStr: parentId, projectId }
    })
  },

  // 重命名文件夹
  rename: (folderId: number | string | bigint, newName: string) => {
    return request({
      url: '/cd/folder/rename',
      method: 'put',
      params: { folderId: String(folderId), newName }
    })
  },

  // 移动文件夹
  move: (folderId: number | string | bigint, targetFolderId: number | string | bigint) => {
    return request({
      url: '/cd/folder/move',
      method: 'post',
      params: { folderId: String(folderId), targetParentId: String(targetFolderId) }
    })
  },

  // 复制文件夹
  copy: (folderId: number | string | bigint, targetFolderId: number | string | bigint) => {
    return request({
      url: '/cd/folder/copy',
      method: 'post',
      params: { folderId: String(folderId), targetParentId: String(targetFolderId) }
    })
  },

  // 删除文件夹
  delete: (folderIds: (number | string | bigint)[]) => {
    const ids = folderIds.map(id => String(id)).join(',')
    return request({
      url: `/cd/folder/${ids}`,
      method: 'delete'
    })
  },

  // 获取文件夹树
  getTree: (userId?: number, projectId?: number) => {
    return request({
      url: '/cd/folder/tree',
      method: 'get',
      params: { userId, projectId }
    })
  },

  // 查询文件夹列表
  list: (params: FolderQuery) => {
    return request({
      url: '/cd/folder/list',
      method: 'get',
      params
    })
  },

  // 获取文件夹详情
  getInfo: (folderId: number | string | bigint) => {
    return request({
      url: `/cd/folder/${String(folderId)}`,
      method: 'get'
    })
  },

  // 检查文件夹权限
  checkPermission: (folderId: number | string | bigint, permissionType: string) => {
    return request({
      url: `/cd/folder/permission/${String(folderId)}`,
      method: 'get',
      params: { permissionType }
    })
  },

  // 更新文件夹统计
  updateStats: (folderId: number | string | bigint) => {
    return request({
      url: `/cd/folder/updateStats/${String(folderId)}`,
      method: 'post'
    })
  },

  // 获取用户根文件夹
  getUserRoot: (userId: number | string | bigint) => {
    return request({
      url: '/cd/folder/userRoot',
      method: 'get',
      params: { userId: String(userId) }
    })
  },

  // 获取项目根文件夹
  getProjectRoot: (projectId: number | string | bigint) => {
    return request({
      url: '/cd/folder/projectRoot',
      method: 'get',
      params: { projectId: String(projectId) }
    })
  }
}

/**
 * 分享管理API
 */
export const shareApi = {
  // 创建分享
  create: (params: ShareCreateParams) => {
    return request({
      url: '/cd/share/create',
      method: 'post',
      params
    })
  },

  // 获取分享信息
  getInfo: (shareCode: string) => {
    return request({
      url: `/cd/share/info/${shareCode}`,
      method: 'get'
    })
  },

  // 验证分享密码
  validatePassword: (shareCode: string, password?: string) => {
    return request({
      url: '/cd/share/validatePassword',
      method: 'post',
      params: { shareCode, password }
    })
  },

  // 更新分享设置
  update: (params: ShareUpdateParams) => {
    return request({
      url: '/cd/share/update',
      method: 'put',
      params
    })
  },

  // 删除分享
  delete: (shareId: number) => {
    return request({
      url: `/cd/share/${shareId}`,
      method: 'delete'
    })
  },

  // 获取用户分享列表
  getUserShares: (userId: number) => {
    return request({
      url: '/cd/share/userShares',
      method: 'get',
      params: { userId }
    })
  },

  // 清理过期分享
  cleanExpired: () => {
    return request({
      url: '/cd/share/cleanExpired',
      method: 'post'
    })
  }
}

/**
 * 存储管理API
 */
export const storageApi = {
  // 获取用户存储统计
  getUserStorage: () => {
    return request({
      url: '/cd/storage',
      method: 'get'
    })
  },

  // 同步用户存储统计（根据实际文件数据重新计算）
  syncStorage: () => {
    return request({
      url: '/cd/storage/sync',
      method: 'post'
    })
  },

  // 获取所有用户的存储统计（管理员功能）
  getAllUserStorage: () => {
    return request({
      url: '/cd/storage/admin/list',
      method: 'get'
    })
  },

  // 管理员设置用户存储配额
  setUserStorageQuota: (userId: number | string | bigint, totalSize: number) => {
    return request({
      url: '/cd/storage/admin/setQuota',
      method: 'post',
      params: { userId: String(userId), totalSize }
    })
  },

  // 管理员初始化用户存储统计
  initUserStorage: (userId: number | string | bigint) => {
    return request({
      url: '/cd/storage/admin/initUserStorage',
      method: 'post',
      params: { userId: String(userId) }
    })
  }
}

/**
 * 权限管理API
 */
export interface PermissionGrantParams {
  userId?: number | string | bigint
  roleId?: number | string | bigint
  resourceType: string
  resourceId: number | string | bigint
  permissionTypes: string[]
}

export interface PermissionParams {
  resourceType: string
  resourceId: number | string | bigint
  permissionId?: number | string | bigint
  userId?: number | string | bigint
  roleId?: number | string | bigint
  permissionType: string
  grantType: 'user' | 'role'
  status?: string
}

export const permissionApi = {
  // 获取资源权限列表
  getResourcePermissions: (resourceType: string, resourceId: number | string | bigint) => {
    return request({
      url: '/cd/permission/getResourcePermissions',
      method: 'get',
      params: { resourceType, resourceId: String(resourceId) }
    })
  },

  // 添加权限
  add: (params: PermissionParams) => {
    return request({
      url: '/cd/permission',
      method: 'post',
      data: params
    })
  },

  // 更新权限
  update: (params: PermissionParams) => {
    return request({
      url: '/cd/permission',
      method: 'put',
      data: params
    })
  },

  // 删除权限
  delete: (permissionIds: (number | string | bigint)[]) => {
    const ids = permissionIds.map(id => String(id)).join(',')
    return request({
      url: `/cd/permission/${ids}`,
      method: 'delete'
    })
  },

  // 为用户授权
  grantUserPermission: (params: PermissionGrantParams) => {
    return request({
      url: '/cd/permission/grantUserPermission',
      method: 'post',
      params: {
        userId: String(params.userId),
        resourceType: params.resourceType,
        resourceId: String(params.resourceId)
      },
      data: params.permissionTypes
    })
  },

  // 为角色授权
  grantRolePermission: (params: PermissionGrantParams) => {
    return request({
      url: '/cd/permission/grantRolePermission',
      method: 'post',
      params: {
        roleId: String(params.roleId),
        resourceType: params.resourceType,
        resourceId: String(params.resourceId)
      },
      data: params.permissionTypes
    })
  },

  // 撤销用户权限
  revokeUserPermission: (params: PermissionGrantParams) => {
    return request({
      url: '/cd/permission/revokeUserPermission',
      method: 'post',
      params: {
        userId: String(params.userId),
        resourceType: params.resourceType,
        resourceId: String(params.resourceId)
      },
      data: params.permissionTypes
    })
  },

  // 撤销角色权限
  revokeRolePermission: (params: PermissionGrantParams) => {
    return request({
      url: '/cd/permission/revokeRolePermission',
      method: 'post',
      params: {
        roleId: String(params.roleId),
        resourceType: params.resourceType,
        resourceId: String(params.resourceId)
      },
      data: params.permissionTypes
    })
  }
}
